package com.estore.network;
import com.estore.model.Product;
import com.estore.service.ProductService;

import java.io.*;
import java.net.*;
import java.util.List;


public class EStoreServer {
    private ProductService productService;

    public EStoreServer() {
        this.productService = new ProductService();
    }

    public static void main(String[] args) {
        EStoreServer server = new EStoreServer();

        try (ServerSocket serverSocket = new ServerSocket(8888)) {
            System.out.println("服务器已启动，监听端口 8888...");

            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端已连接: " + clientSocket.getInetAddress());

                // 处理客户端请求
                server.handleClient(clientSocket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void handleClient(Socket clientSocket) {
        try (
                ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream());
                ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream())
        ) {
            // 读取客户端发送的请求
            String request = (String) input.readObject();
            System.out.println("收到客户端请求: " + request);

            // 根据请求类型调用相应的方法
            if ("GET_ALL_PRODUCTS".equals(request)) {
                List<Product> products = productService.getAllProducts();
                output.writeObject(products);
            } else {
                // 处理其他可能的请求类型
                output.writeObject("未知请求");
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}